package com.tomato.tv.activity

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.rtsp.RtspMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.tomato.tv.R
import kotlinx.android.synthetic.main.activity_play.*

class ExoPlayerActivity : AppCompatActivity(), Player.Listener {

    private lateinit var player1: ExoPlayer
    private lateinit var player2: ExoPlayer
    // private val url = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4"
    //private val url = "https://media.w3.org/2010/05/sintel/trailer.mp4"
    // private val url = "rtsp://192.168.4.188:8554/lonbon"
    private val url = "rtsp://admin:1111@192.168.4.141:554/1"
    //private val url = "http://219.151.31.38/liveplay-kk.rtxapp.com/live/program/live/hnwshd/4000000/mnf.m3u8"
    //private val url = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play)

        player1 = ExoPlayer.Builder(this).build()
        player1.addListener(this)
        videoView1.player = player1
        initPlayer(player1)

        player2 = ExoPlayer.Builder(this).build()
        player2.addListener(this)
        videoView2.player = player2
        initPlayer(player2)

        /*player3 = ExoPlayer.Builder(this).build()
        player3.addListener(this)
        videoView3.player = player3
        initPlayer(player3)

        player4 = ExoPlayer.Builder(this).build()
        player4.addListener(this)
        videoView4.player = player4
        initPlayer(player4)*/
    }

    private fun initPlayer(player: ExoPlayer) {
        val mediaSource =
            RtspMediaSource.Factory().setForceUseRtpTcp(true).setDebugLoggingEnabled(true)
                .createMediaSource(MediaItem.fromUri(url))
        player.setMediaSource(mediaSource)
        player.playWhenReady = true
        player.prepare()
    }

    override fun onDestroy() {
        //videoView.suspend();
        player1.stop()
        player1.release()

        player2.stop()
        player2.release()
        super.onDestroy()
    }

    override fun onPlayerError(error: PlaybackException) {
        Log.w("ExoPlayerActivity", "error:" + error.message)
    }
}